import { NextResponse } from "next/server"
import { getServerUser } from "@/lib/session"
import { tagZodFormData, z} from '@/shared/formDataSchema'
import { findSameNameTag, createTag } from '@/server/database/repositories/tag'

export async function POST( req: Request) {
  try{
    const body = await req.json()
    const {name,sign,kind} = body
    tagZodFormData.parse(body)

    const user = await getServerUser() as User
    const {id: user_id} = user
    const hasSame = await findSameNameTag({name,sign,kind,user_id})
    if(hasSame){
      return NextResponse.json('已存在同类同名标签名称',{status: 400})
    }
    const tag = await createTag({name,sign,kind,user_id})
    if(!tag) {
      return NextResponse.json('创建标签失败',{status: 400})
    }
    return NextResponse.json({msg: '创建标签成功!'})
  } catch (error) {
    if (error instanceof z.ZodError) {
      // 如果验证失败，返回具体的错误信息
      const statusMessage = error.issues.map(issue => issue.message).join("; ");
      // 返回错误信息和状态码
      return NextResponse.json( statusMessage, { status: 400} )
    }
    return NextResponse.json( '服务器出错，创建标签失败！', { status: 500} )
  }
}